#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>

#define SERVER_IP "127.0.0.1"  //服务器ip地址
#define SERVPORT "12306"   //port端口号
#define BUFFER_SIZE 1024  // 缓冲区大小

int downloadFileToLocal(const char *fileName);

int main(int argc,char *argv[])
{
	if (argc != 2) {   //  
		printf("Usage: %s <filename>\n", argv[0]);
		exit(1);
	}

	const char *fileName = argv[1];   //获取文件名称
	downloadFileToLocal(fileName);  //执行下载操作
    
    return 0;
}



/* 从服务器端下载文件到本地*/
int downloadFileToLocal(const char *fileName) {
	int sockfd;   //socket通信
	struct sockaddr_in server_Address;  //ip的默认配置
	char buffer[BUFFER_SIZE];   //下载时文件的缓冲区
	int bytesReceived = 0;     //已经接受的文件字节
	FILE *fp;       //文件指针

	// 创建套接字  
	sockfd = socket(AF_INET, SOCK_STREAM, 0);   
	if (sockfd < 0) {
		perror("Error in socket creation");
		return -1;
	}

	//配置服务器地址   
	server_Address.sin_family = AF_INET;
	server_Address.sin_port = htons(SERVER_PORT);
	server_Address.sin_addr.s_addr = inet_addr(SERVER_IP);

	// 连接到服务器  
	if (connect(sockfd, (struct sockaddr *)&server_Address, sizeof(server_Address)) < 0) {
		perror("Error in connecting to server");
		return -1;
	}

	// 向服务器发送文件下载请求
	snprintf(buffer, BUFFER_SIZE, "GET %s \r\n\r\n", fileName);
	send(sockfd, buffer, strlen(buffer), 0); 

	// 打开文件进行写入
	fp = fopen(fileName, "wb");   
	if (fp == NULL) {
		perror("Error in opening file");
		return -1;
	}

	// 接收文件内容
	memset(buffer, 0, BUFFER_SIZE);  //将buffer数组的所有字节都设置为0，确保内存区域是干净的，没有残留的旧数据
	while ((bytesReceived = read(sockfd, buffer, BUFFER_SIZE)) > 0) {   //read函数的返回值是实际读取的字节数，如果大于0，表示成功读取了数据。
		fwrite(buffer, 1, bytesReceived, fp);  //将bytesReceived读到的数据存到buffer指针指向的文件
	}

	if (bytesReceived < 0) {
		perror("Error in reading data");
	}

	// 关闭文件和套接字
	fclose(fp);
	close(sockfd);

	printf("File %s downloaded successfully.\n", fileName);


	return 0;
}


